package com.example.mybatisplusdemo.web.controller;

import com.example.mybatisplusdemo.common.utls.SessionUtils;
import com.example.mybatisplusdemo.model.domain.User;
import com.example.mybatisplusdemo.model.dto.ApproveRechargeDTO;
import com.example.mybatisplusdemo.model.dto.RechargeRequestDTO;
import org.springframework.web.bind.annotation.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplusdemo.common.JsonResponse;
import com.example.mybatisplusdemo.service.IRechargeService;
import com.example.mybatisplusdemo.model.domain.Recharge;

import java.util.List;


/**
 *
 *  前端控制器
 *
 *
 * @author lqj
 * @since 2025-07-01
 * @version v1.0
 */
@RestController
@RequestMapping("/api/recharge")
public class RechargeController {

    private final Logger logger = LoggerFactory.getLogger( RechargeController.class );

    @Autowired
    private IRechargeService rechargeService;

    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse<Recharge> getById(@PathVariable("id") Long id)throws Exception {
        Recharge recharge = rechargeService.getById(id);
        return JsonResponse.success(recharge);
    }


    // 充值请求列表
    @GetMapping("/list")
    public JsonResponse<List<Recharge>> listAllRechargeRequests() {
        List<Recharge> list = rechargeService.getAllPendingOrHandled();
        return JsonResponse.success(list);
    }

    // 审批充值请求
    @PostMapping("/approve")
    public JsonResponse<String> approveRequest(@RequestBody ApproveRechargeDTO dto) {
        boolean success = rechargeService.approve(dto.getRequestId(), dto.isApproved());
        if (success) {
            return JsonResponse.success("审批成功");
        } else {
            return JsonResponse.failure("请求不存在或已处理");
        }
    }

    @PostMapping("/request")
    public JsonResponse<String> requestRecharge(@RequestBody RechargeRequestDTO dto) {
        User user = SessionUtils.getCurrentUserInfo();
        if (user == null) {
            return JsonResponse.failure("请先登录");
        }

        rechargeService.saveRechargeRequest(user.getId(), dto.getAmount());
        return JsonResponse.success("充值请求提交成功，请等待审核");
    }
    @DeleteMapping("/clear")
    public JsonResponse<String> clearProcessedRecharge() {
        // 删除所有状态不为0的充值记录
        int rows = rechargeService.clearProcessed(); // 调用 service 层方法
        return JsonResponse.success("清除成功，共删除 " + rows + " 条已处理记录");
    }

}

